#!/usr/bin/perl # for syntax highlighting
# CSS-V1
# vim: ts=4:sw=4:syntax=perl

# Generate a table with a list of check boxes - each one 
# is the name of the report which it applies to. If the
# same report is in multiple portals the user has acces
# to only one is shown.

use gri_macro_handler qw(html_error);
use gri_secmgr qw(get_cookie_value);
use gri_user_alert_config;

sub mm_show_reports_alerting_form {
my $given_user=shift;
my %reports_list=();

	# Get the username from the cookie


	my $v=get_cookie_value(name=>"gri_dbm_intranet");
	if(defined($given_user)) {
		$v=hex_to_string($given_user);
	}
	$v =~ s/\s+.*//;
	my $alerts_dir=$::GRI_FRONTEND->get_global_directory("alerts");
	my $user_alerting;
	if(-f "$alerts_dir/$v.config.xml") {
		$user_alerting=new gri_user_alert_config("$alerts_dir/$v.config.xml");
	} else {
		$user_alerting=new gri_user_alert_config();
	} 
	my $lref=$::GRI_FRONTEND->get_portal_list();
	my @L=(@$lref);

	#########################################################
	# We simply show the list of reports in a mini-table.	#
	#########################################################

	my @REPS=$user_alerting->get_report_names();
	my $str="<tr class=gri_headerrow><td class=gri_cell>Report Description</td><td class=gri_cell-right>Alerting</td></tr>\n";
	my $row=0;
	my $class="odd";
	# We build up a list of entries with the text, portal and report details
	# so we can sort them before showing them to make things easier.
	my %stuff=();
	my @errors=();
	for my $c (@L) {
		my $a=$::GRI_FRONTEND->is_user_allowed($c,$v);
		next if !$a;
		my $portal_fname=$::GRI_FRONTEND->get_portal_filename($c);
		my ($lref,$err)=$::GRI_FRONTEND->get_portal_report_names($c);
		if($lref) {
			my @L2=@$lref;
			for my $rep (@L2) {
				my @info=$::GRI_FRONTEND->get_portal_report_details($c,$rep);
				if(!$info[0]) {
					push @errors,[$c,$rep,$info[5]];
					next;
				}
				$stuff{$rep}={
					text => $info[0],
					name => "AL_$rep",
					value => "$rep~$portal_fname",
					portal => $portal_fname,
				};
			}
		}
	}
	my @_slist=sort {lc($stuff{$a}->{text}) cmp lc($stuff{$b}->{text});} keys(%stuff);
	for my $ckey (@_slist) {
		my $portal_fname=$stuff{$ckey}->{portal};

		$class="gri_odd";
		$class="gri_even" if $row%2==0;
		next if exists($reports_list{$ckey});
		if(!defined($stuff{$ckey}->{text})) {
		}
		$str.="
  <tr id=$class><td class=gri_cell valign=top>$stuff{$ckey}->{text}</td>
    <td class=gri_cell-right><input type=\"checkbox\" name=\"$stuff{$ckey}->{name}\" value=\"$stuff{$ckey}->{value}\"";
		if(grep {$_ eq $ckey} @REPS) {
			$str.=" checked=\"y\"></td></tr>\n";
		} else {
			$str.="></td></tr>\n";
		}
		$row++;
	}
	my $u2=string_to_hex($v);
	$str.="<input type=hidden name=user value=\"$u2\">";
	my $str2="";
	for my $ce (@errors) {
		$str2.=html_error("Portal '$ce->[0]', Report '$ce->[1]', Error: $ce->[2]",0);
	}

	return "<table class=gri_container>\n$str</table>$str2";
}

# vim: ts=4:sw=4
